package servlet;

import dao.ArticleDao;
import dao.CommentDao;
import dao.daoimpl.ArticleDaoImpl;
import dao.daoimpl.CommentDaoImpl;
import bean.Comment;
import bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "AddCommentServlet",urlPatterns = "/AddCommentServlet")
public class AddCommentServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");/*防止乱码*/
        CommentDao commentDao=new CommentDaoImpl();
        ArticleDao articleDao=new ArticleDaoImpl();
        String commentContent=request.getParameter("addArticleCommentContent");/*获取评论内容*/
        System.out.println(commentContent);
        int articleId=Integer.parseInt(request.getParameter("addArticleCommentId"));/*获取文章id*/
        int fatherId=Integer.parseInt(request.getParameter("addArticleCommentFatherId"));/*获取一级评论id*/
        User user=(User)request.getSession().getAttribute("user");/*获取用户*/
        String time=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date());/*获取当前时间*/
        Comment comment=new Comment(fatherId,commentContent,time,articleId,user.getAccount(),user.getHeadPortrait());
        if(commentDao.addComment(comment)) {
            System.out.println("用户评论成功");
            try {
                request.getSession().setAttribute("blogComments", commentDao.getComments(articleId));/*更新*/
                request.getSession().setAttribute("blogArticle",articleDao.getArticle(articleId));
                response.sendRedirect(request.getContextPath() + "/blogPage.jsp");
            } catch (SQLException sqlException) {
                sqlException.printStackTrace();
            }
        }else{
            System.out.println("用户评论失败");
        }
    }
}
